package com.gxuwz.mxb.lph.controller;

import com.gxuwz.mxb.lph.config.SystemContext;
import com.gxuwz.mxb.lph.entity.User;
import com.gxuwz.mxb.lph.entity.UserRole;
import com.gxuwz.mxb.lph.service.RoleService;
import com.gxuwz.mxb.lph.service.UserRoleService;
import com.gxuwz.mxb.lph.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Controller
public class LoginController {
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private UserRoleService userRoleService;

    @RequestMapping("/login")
    public String login(String userId, String userPassword, HttpServletRequest request, Model model) {
        User user = userService.findUserByUserId(userId);
        UserRole userRole =userRoleService.findUserRoleByUserId(userId);
        if(user != null && user.getUserPassword() != null) {

            // 判断用户密码是否正确
            boolean isLogin = SystemContext.passwdDecryption(userPassword, user.getUserPassword());
            if(isLogin) {
                // 将用户信息存入session
                request.getSession().setAttribute("userInfo", user);
                // 将用户拥有菜单权限列表存入session
                List<String> listRight = roleService.getUserPermissions(user.getUserId()+"");
                request.getSession().setAttribute("listRight", listRight);

                model.addAttribute(user);
                model.addAttribute("userRole",userRole);
//                model.addAttribute("userId",userId=null);
                return "main";
            }
        }

        return "../../login";
    }
    @RequestMapping("/openWelcomePage")
    public String openWelcomePage(Model model) {
        return "welcome";
    }
}